package com.base.activity;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.v4.view.ViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;

import com.base.R;
import com.base.displaymetrics.AutoSize;
import com.base.displaymetrics.ResourcesWrapper;
import com.base.fragment.BaseDialogFragment;
import com.base.widget.TitleBar;
import com.uitls.utils.DisplayUtils;

import java.lang.reflect.Field;

public abstract class BaseActivity extends AppCompatActivity {
    private View mContentView;  //除标题栏外的view
    private TitleBar mTitleBar; //标题栏

    protected boolean mResumed;
    private BaseDialogFragment loadingDialog;
    private static final String DIALOG_TAG_LOADING = "dialog_loading";//;oading
    protected Context mContext;
    private ResourcesWrapper mResources;

    private void translucentStatusBar() {
        Window window = getWindow();
        //添加Flag把状态栏设为可绘制模式
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            //如果为全透明模式，取消设置Window半透明的Flag
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //设置状态栏为透明
            window.setStatusBarColor(Color.TRANSPARENT);
            //设置window的状态栏不可见
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //如果为半透明模式，添加设置Window半透明的Flag
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //设置系统状态栏处于可见状态
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
        }
        //view不根据系统窗口来调整自己的布局
        ViewGroup mContentView = (ViewGroup) window.findViewById(Window.ID_ANDROID_CONTENT);
        View mChildView = mContentView.getChildAt(0);
        if (mChildView != null) {
            ViewCompat.setFitsSystemWindows(mChildView, false);
            ViewCompat.requestApplyInsets(mChildView);
        }
    }

//    private void translucentStatusBar(Activity activity) {
//        Window window = activity.getWindow();
//        //设置Window为透明
//        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//
//        ViewGroup mContentView = (ViewGroup) activity.findViewById(Window.ID_ANDROID_CONTENT);
//        View mContentChild = mContentView.getChildAt(0);
//
//        //移除已经存在假状态栏则,并且取消它的Margin间距
//        removeFakeStatusBarViewIfExist(activity);
//        removeMarginTopOfContentChild(mContentChild, getStatusBarHeight());
//        if (mContentChild != null) {
//            //fitsSystemWindow 为 false, 不预留系统栏位置.
//            ViewCompat.setFitsSystemWindows(mContentChild, false);
//        }
//    }
//
//    private static void removeMarginTopOfContentChild(View mContentChild, int statusBarHeight) {
//        if (mContentChild == null) {
//            return;
//        }
//        if ("marginAdded".equals(mContentChild.getTag())) {
//            FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mContentChild.getLayoutParams();
//            lp.topMargin -= statusBarHeight;
//            mContentChild.setLayoutParams(lp);
//            mContentChild.setTag(null);
//        }
//    }
//
//    private static void removeFakeStatusBarViewIfExist(Activity activity) {
//        Window window = activity.getWindow();
//        ViewGroup mDecorView = (ViewGroup) window.getDecorView();
//
//        View fakeView = mDecorView.findViewWithTag("statusBarView");
//        if (fakeView != null) {
//            mDecorView.removeView(fakeView);
//        }
//    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        if (isInterceptCreate()) {
            return;
        }
        if (isSetDecorViewBackground()) {
            getDecorView().setBackgroundResource(R.drawable.ui_bg);
        }
        if (isTranslucentStatus()) {
            try {
                translucentStatusBar();
            } catch (Exception e) {
                //https://bugly.qq.com/v2/crash-reporting/crashes/4604733b90/9859?pid=1
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
                localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
            }
        }
        int layoutId = getLayoutId();
        if (layoutId > 0) {
            setContentView(layoutId);
            initView(savedInstanceState);
            findScrollView();
        }
    }

    //是否拦截onCreate事件
    protected boolean isInterceptCreate() {
        return false;
    }

    public void comeBack() {
        finish();
    }

    @Override
    final public void setContentView(@LayoutRes int layoutResID) {
        if (layoutResID != 0) {
            mContentView = inflate(layoutResID, null);
        } else {
            mContentView = getCustomView();
        }
        if (useDynamicTitleBar()) { //动态添加标题栏
            View titleBar = getCustomTitleBar();
            if (titleBar == null) {
                mTitleBar = new TitleBar(this);

                if (!isSetDecorViewBackground()) {  //没有设置DecorView背景，则设置titleBar背景
                    mTitleBar.setBackgroundResource(R.drawable.ui_bg);
                }
                titleBar = mTitleBar;
                if (useLeftDefaultIcon()) {
                    //增加返回按钮
                    mTitleBar.setLeftImageResource(R.mipmap.ic_back);
                    mTitleBar.setLeftImageOnClickListener(new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            comeBack();
                        }
                    });
                }
            }
//            titleBar.setBackgroundColor(Color.TRANSPARENT);
            if (isTranslucentStatus()) {
//            titleBar.setFitsSystemWindows(true);
                titleBar.setPadding(0, getStatusBarHeight(), 0, 0);
            }
            LinearLayout linearLayout = new LinearLayout(this);
            linearLayout.setOrientation(LinearLayout.VERTICAL);
            //添加标题栏
            linearLayout.addView(titleBar, new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));

            //添加view
            linearLayout.addView(mContentView, new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));

            super.setContentView(linearLayout);
        } else {
            super.setContentView(mContentView);
        }
    }

    //4.4以上才返回状态栏高度
    public int getStatusBarHeight() {
        int result = 0;
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = getResources().getDimensionPixelSize(resourceId);
        }
        if (result == 0) {
            Class c;
            try {
                c = Class.forName("com.android.internal.R$dimen");
                Object obj = c.newInstance();
                Field field = c.getField("status_bar_height");
                int x = Integer.parseInt(field.get(obj).toString());
                result = getResources().getDimensionPixelSize(x);
            } catch (Exception ignore) {

            }
        }
        if (result == 0) {
            result = (int) Math.ceil(20 * getResources().getDisplayMetrics().density);
        }
        return result;
    }

    /**
     * 设置布局,如果子类不想设置，返回0就可以
     */
    protected abstract @LayoutRes
    int getLayoutId();

    /**
     * 初始化控件
     */
    protected abstract void initView(Bundle savedInstanceState);

    //是否透明状态栏
    protected boolean isTranslucentStatus() {
        return true;
    }

    //是否设置DecorView背景
    protected boolean isSetDecorViewBackground() {
        return true;
    }

    /**
     * 默认使用动态的titlebar，如果特殊情况不使用，需复写此方法，并返回false
     */
    protected boolean useDynamicTitleBar() {
        return true;
    }

    /**
     * 默认使用titlebar的左侧关闭按钮
     */
    protected boolean useLeftDefaultIcon() {
        return true;
    }

    protected boolean autoFindScrollView() {
        return true;
    }

    /**
     * 复写此方法，返回自定义的titlebar
     *
     * @return 返回自定义的titleBar
     */
    protected View getCustomTitleBar() {
        return null;
    }

    protected View getCustomView() {
        return null;
    }

    /**
     * 动态加载布局文件
     *
     * @param layoutResID
     * @param root
     * @return
     */
    protected View inflate(int layoutResID, ViewGroup root) {
        return LayoutInflater.from(this).inflate(layoutResID, root);
    }

    /**
     * 查找控件
     *
     * @param id
     * @return
     */
    protected <T extends View> T $(int id) {
        return (T) findViewById(id);
    }

    protected <T extends View> T $(int id, View view) {
        return (T) view.findViewById(id);
    }

    protected View getContentView() {
        return mContentView;
    }

    protected View getDecorView() {
        return getWindow().getDecorView();
    }

    public TitleBar getTitleBar() {
        return mTitleBar;
    }

    protected void setTitleBar(TitleBar titleBar) {
        mTitleBar = titleBar;
    }

    /**
     * 设置title
     * 如果不是用默认的TitleBar，不能设置此属性
     *
     * @param title
     */
    @Override
    public void setTitle(CharSequence title) {
        if (mTitleBar != null) {
            mTitleBar.setTitle(title);
        } else {
            throw new IllegalStateException("你没有使用默认的TitleBar，不能使用此方法设置标题");
        }
    }

    @Override
    public void setTitle(int titleId) {
        setTitle(getText(titleId));
    }

    /**
     * 遍历找到viewGroup下面的第一个可滑动的View
     */
    private void findScrollView() {
        if (autoFindScrollView() && useDynamicTitleBar()) {
            View canScrollView = DisplayUtils.findFirstCanScrollView((ViewGroup) getContentView());
            if (canScrollView != null) {
                setSmoothToTopView(canScrollView);
            }
        }
    }

    public void setSmoothToTopView(View canScrollView) {
        if (mTitleBar != null) {
            mTitleBar.setSmoothToTopView(canScrollView);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        mResumed = false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        mResumed = true;
    }

    @Override
    public boolean isDestroyed() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            return super.isDestroyed();
        } else {
            return isFinishing();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        release();
    }

    protected abstract void release();

    /**
     * 今日头条适配
     *
     * @return
     */
    @Override
    public Resources getResources() {
        if (mResources == null) {
            final AutoSize autoSize = getAutoSize();
            mResources = new ResourcesWrapper(super.getResources(), autoSize);
        }
        return mResources;
    }

    /**
     * @return
     */
    private AutoSize getAutoSize() {
        return new AutoSize(375/*设计的宽度dp*/, true);
    }
}
